import { layout } from "@/styles/variables";
import { getFullscreenStatus, triggerScreen } from "@/utils/fullscreen";
import { baseStorage } from "@/utils/storage";
import { defineStore } from "pinia";
import { computed, reactive, ref, toRefs, watch } from "vue";

export const APP_STORE = "app";

export enum ZLang {
  ZH_CN,
  EN,
}

interface ZAppState {
  collapsed: boolean;
  zenMode: boolean;
  darkTheme: boolean;
  language: ZLang;
}

interface ZAppStyleState {
  footerHeight: string;
  contentPadding: string;
}

export const useAppStore = defineStore(APP_STORE, () => {
  const cache = baseStorage.get<ZAppState>(APP_STORE);
  const appState = reactive<ZAppState>({
    collapsed: cache?.collapsed ?? false,
    zenMode: cache?.zenMode ?? false,
    darkTheme: cache?.darkTheme ?? false,
    language: cache?.language ?? ZLang.ZH_CN,
  });

  watch(appState, () => {
    baseStorage.set(APP_STORE, appState);
  });

  // menu collapsed
  function triggerCollapse() {
    appState.collapsed = !appState.collapsed;
  }
  function setCollapsed(folded = true) {
    appState.collapsed = folded;
  }

  // zen mode
  function setZenMode(isZen = true) {
    appState.zenMode = isZen;
  }
  function triggerZenMode() {
    appState.zenMode = !appState.zenMode;
  }

  // dark theme
  function setTheme(isDark = false) {
    appState.darkTheme = isDark;
  }

  // language
  function setLanguage(lang = ZLang.ZH_CN) {
    appState.language = lang;
  }
  const isLangZhCn = computed(() => appState.language === ZLang.ZH_CN);

  // fullscreen
  const fullscreen = ref(false);
  function triggerFullscreen() {
    triggerScreen(fullscreen.value);
  }
  function updateFullScreen() {
    fullscreen.value = getFullscreenStatus();
  }
  function setupScreenListener() {
    window.addEventListener("fullscreenchange", updateFullScreen);
  }
  function removeScreenListener() {
    window.addEventListener("fullscreenchange", updateFullScreen);
  }

  const appStyleState = reactive<ZAppStyleState>({
    footerHeight: layout["footer-height"],
    contentPadding: layout["content-padding"],
  });
  function setFooterHeight(hideFooter = false) {
    appStyleState.footerHeight = hideFooter ? "0px" : layout["footer-height"];
  }
  function setContentPadding(padding = layout["content-padding"]) {
    appStyleState.contentPadding = padding;
  }

  return {
    ...toRefs(appState),
    triggerCollapse,
    setCollapsed,
    setZenMode,
    triggerZenMode,
    setTheme,
    isLangZhCn,
    setLanguage,
    fullscreen,
    triggerFullscreen,
    setupScreenListener,
    removeScreenListener,

    ...toRefs(appStyleState),
    setFooterHeight,
    setContentPadding,
  };
});
